import { loadEnv, defineConfig } from 'vite'
import { wrapperEnv } from './build/utils'
import vue from '@vitejs/plugin-vue2'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Unocss from 'unocss/vite'
import { ElementUiResolver } from 'unplugin-vue-components/resolvers'
import { resolve } from 'path'
import { createHtmlPlugin } from 'vite-plugin-html'

import pkg from './package.json'

function pathResolve(dir) {
  return resolve(process.cwd(), '.', dir)
}

export default defineConfig((mode, command) => {
  const root = process.cwd()
  const env = loadEnv(mode, root)

  // loadEnv读取的布尔类型是一个字符串。这个函数可以转换为布尔类型
  const viteEnv = wrapperEnv(env)
  const { VITE_PUBLIC_PATH, VITE_GLOB_APP_TITLE, VITE_APP_CONFIG_FILE_NAME } =
    viteEnv

  const path = VITE_PUBLIC_PATH.endsWith('/')
    ? VITE_PUBLIC_PATH
    : `${VITE_PUBLIC_PATH}/`

  const getAppConfigSrc = () => {
    return `${path || '/'}${VITE_APP_CONFIG_FILE_NAME}?v=${
      pkg.version
    }-${new Date().getTime()}`
  }

  const isBuild = command === 'build'
  return {
    plugins: [
      vue(),
      Components({
        dirs: ['src/components'],
        extensions: ['vue'],
        deep: true,
        resolvers: [ElementUiResolver()]
      }),
      AutoImport({
        imports: ['vue', 'vue-router'],
        resolvers: [ElementUiResolver()],
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/ // .vue
        ],
        eslintrc: {
          enabled: true, // Default `false`
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        }
      }),
      Unocss({}),
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          // Inject data into ejs template
          data: {
            title: VITE_GLOB_APP_TITLE
          },
          // Embed the generated _app.config.js file, 使用esno编译，npm run build:post
          tags: isBuild
            ? [
                {
                  tag: 'script',
                  attrs: {
                    src: getAppConfigSrc()
                  }
                }
              ]
            : []
        }
      })
    ],
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'element-ui': ['element-ui']
          }
        }
      }
    },
    resolve: {
      alias: {
        '@': pathResolve('src')
      }
    }
  }
})
